﻿
$c.fn.datagrid = function (config) {
    
    var obj = function (selector, config) {
        this.selector = selector;
        this.config = $.extendEx({}, this.defConfig, config);
    }
    obj.prototype.defConfig = {
        queryParams: {
            pageNo: 1,
            pageSize: 15
        },
        pagerConfig: {
            pagerItems: 'page-size-dropdown,|,first,pre,|,goto,|,next,last,|,load,remark',
            pageList:[10,15,20,30,40,50]
        },
        showLoading:true,
        showLoadingDelay: 1000,//单位:毫秒
        showLoadingWindow: window.kwindow //top.kwindow
    };
    obj.prototype.datagrid = function () {
        this.selector.addClass('kui-datagrid');
        this.loadData();
    }
    obj.prototype.loadData = function (config,onLoaded) {//切换分页时，外部调用这个方法即可.
        
        this.config = $.extendEx(this.config, config);
        
        var _obj = this;

        if (_obj.config.data) {
            _obj.draw(data);
        }
        else if (_obj.config.url) {
            var loadingIndex = 0;
            var isLoaded = false;
            if (_obj.config.showLoading == true && _obj.config.showLoadingWindow) {
                if (_obj.config.showLoadingDelay > 0) {
                    var _timeoutID = window.setTimeout(function () {
                        window.clearTimeout(_timeoutID);
                        if (!isLoaded) {
                            loadingIndex = _obj.config.showLoadingWindow.loading(_obj.config.loadingConfig);
                        }
                    }, _obj.config.showLoadingDelay)
                }
                else{
                    loadingIndex = _obj.config.showLoadingWindow.loading(_obj.config.loadingConfig);
                }
            }
            $.post(_obj.config.url, _obj.config.queryParams, function (result, status) {

                isLoaded = true;

                if (result.rows.length == 0 && _obj.config.queryParams.pageNo > 1 && _obj.config.queryParams.pageNo > result.pageTotal) {//最后一页的记录被删光,重新加载前一页.
                    _obj.config.queryParams.pageNo--;
                    _obj.loadData(_obj.config, onLoaded);
                    return;
                }

                _obj.pageResult = result;

                _obj.draw(result.rows);

                if (onLoaded) {
                    onLoaded();
                }

                if (_obj.config.pager) {
                    var pagerConfig = $.extendEx({}, {
                        pageTotal: result.pageTotal,
                        pageNo: result.pageNo,
                        pagerItemClick: function (_pageNo, trigger) {
                            if ($(trigger).hasClass('kui-pager-item-load')) {
                                $(trigger).removeClass('kui-pager-item-load');
                                $(trigger).addClass('kui-pager-item-loading');
                            }
                            _obj.loadData({ queryParams: { pageNo: _pageNo } });
                        },
                        onPageSizeChange:function(elem,o){
                            _obj.loadData({ queryParams: { pageNo: 1, pageSize: o.value} })
                        },
                        prevPageText: '',
                        firstPageText: '',
                        nextPageText: '',
                        lastPageText: ''
                    }, _obj.config.pagerConfig, { pageSize: _obj.config.queryParams.pageSize });

                    var pager = $c(_obj.config.pager).pager(pagerConfig);
                    var recordStartNo = ((result.pageNo - 1) * result.pageSize + 1);
                    
                    pager.addRemark('显示' + recordStartNo + '到' + (recordStartNo + result.rows.length - 1) + ',共' + result.rowTotal + '记录');
                }

                if (loadingIndex > 0) {
                    _obj.config.showLoadingWindow.close(loadingIndex);
                }
            });
        }
    }
    obj.prototype.checkAll = function (isCheck) {
        var _obj = this;
        if (isCheck == undefined) {
            isCheck = true;
        }
        $.each(_obj.selector.find('.kui-tr'), function (i, tr) {
            if (i == 0) {//表头
                return;
            }
            var cb = $(tr).find('.kui-td-checkbox :checkbox');
            if (isCheck) {
                //cb.attr('checked', 'true');
                cb[0].checked = true;
                $(tr).addClass('kui-tr-selected');
            }
            else {
                //cb.removeAttr('checked');
                cb[0].checked = false;
                $(tr).removeClass('kui-tr-selected');
            }
        });
    }
    obj.prototype.checkRow = function (index, isCheck) {
        var _obj = this;
        if (isCheck == undefined) {
            isCheck = true;
        }
        var tr=_obj.selector.find('.kui-tr:eq(' + (index + 1) + ')');
        var cb = tr.find('.kui-td-checkbox :checkbox');
        if (isCheck) {
            cb[0].checked = true;
            tr.addClass('kui-tr-selected');
        }
        else {
            cb[0].checked = false;
            tr.removeClass('kui-tr-selected');
        }
    }
   
    obj.prototype.getChecked = function () {
        var _obj = this;
        var rows = [];
        $.each(_obj.selector.find('.kui-tr'), function (i,tr) {
            if (tr.index==-1) {//表头
                return;
            }
            if ($(tr).find('.kui-td-checkbox :checkbox').is(':checked')) {
                rows.push(tr);
            }
            
        });
        return rows;
    }
    obj.prototype.setRowData=function(index,data){
        var _obj = this;
        var trs = _obj.selector.find('.kui-tr');
        $.each(trs, function (i,tr) {
            if (tr.index != index) {
                return;
            }
            tr.data = data;
            var columns = _obj.config.columns;
            $.each(columns, function (i, column) {
                if (column.checkbox == true||column.rowNo==true) {
                    return;
                }
                var td = $(tr).find('.kui-td-' + (i + 1) + '');
                var formatData = data[column.field];
                if (column.formatter) {
                    formatData = column.formatter(data[column.field], data, index)
                }
                td.find('span').html(formatData);
            });
        });
    }
    obj.prototype.getRows = function () {
        var _obj = this;
        var trs = _obj.selector.find('.kui-tr:not(:eq(0))');
        return trs;
    }
    obj.prototype.getRow = function (index) {
        var _obj = this;
        var trs = _obj.selector.find('.kui-tr');
        var result;
        $.each(trs, function (i, tr) {
            if (tr.index == index) {
                result = tr;
            }
        });
        return result;
    }
    obj.prototype.draw = function (dataList) {
        var _obj = this;
        var columns = _obj.config.columns;
        $(_obj.selector).html('');
        
        //绘制表头
        var tr = $('<div class="kui-tr"></div>').appendTo(this.selector);
        tr[0].index = -1;
        $.each(columns, function (i, column) {
            var _title = column.title;
            var isCheckboxColumn=!column.title && column.checkbox==true;
            if (isCheckboxColumn) {
                _title = '<input type="checkbox"/>';
            }
            var td = $('<div class="kui-td kui-th kui-td-' + (i + 1) + '"><span>' + _title + '</span></div>').appendTo(tr);
            if (isCheckboxColumn) {
                td.addClass('kui-td-checkbox');
                td.find('input').click(function () {
                    _obj.checkAll($(this).is(':checked'));
                });
            }
            if (column.width) {
                td.width(column.width);
                //td.css('width', column.width);
            }
            if (column.fixColWidth == true) {
                td.attr('fixColWidth', 1);
            }
            if (column.hidden == true) {
                td.css('display', 'none');
            }
        });
        tr.append('<div class="clear"></div>');
        
        //绘制数据行
        $.each(dataList, function (dataIndex, data) {
            var tr = $('<div class="kui-tr"></div>').appendTo(_obj.selector);
            tr[0].index = dataIndex;
            tr[0].data = data;
            if (dataIndex % 2 == 1) {
                tr.addClass('kui-odd');
            }
            $.each(columns, function (colIndex, column) {
                var formatData = null;
                if (column.rowNo == true) {
                    formatData = (_obj.pageResult.pageNo - 1) * _obj.pageResult.pageSize + dataIndex + 1;//行号
                }
                else if (column.checkbox == true) {
                    formatData = '<input type="checkbox"/>';
                }
                else if (column.formatter) {
                    formatData = column.formatter(data[column.field],data,dataIndex)
                }
                else {
                    formatData = data[column.field];
                }
                if (formatData == null || formatData == undefined) {
                    formatData = '';
                }
                var td = $('<div class="kui-td kui-td-' + (colIndex + 1) + '"><span>' + formatData + '</span></div>').appendTo(tr);
                if (column.rowNo == true) {
                    td.addClass('kui-td-rowno');
                }
                if (column.checkbox == true) {
                    td.addClass('kui-td-checkbox');
                    td.find('input').click(function () {
                        if ($(this).is(':checked')) {
                            tr.addClass('kui-tr-selected');
                        }
                        else {
                            tr.removeClass('kui-tr-selected');
                        }
                    });
                }
                if (column.hidden == true) {
                    td.css('display', 'none');
                }
            });
            tr.append('<div class="clear"></div>');
        });

        if (!_obj.divTableObj) {
            _obj.divTableObj=$c(_obj.selector).table(this.config);
        }
        else {
            _obj.divTableObj.table();
        }

        if (_obj.config.onLoaded) {
            _obj.config.onLoaded(_obj);
        }
    }

    var _obj = new obj($(this.jo), config || {});
    _obj.datagrid();

    return _obj;
};